package search;

/**
 * 二分查找，要求数组是已排序的
 *
 * @author zj
 */
public class BinSearch {
    private static int A[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
    private static int count = 0;

    public static void main(String[] args) {
        System.out.println(binSearch(A, 10));
        System.out.println("查找了" + count + "次");
    }

    private static int binSearch(int A[], int k) {
        int low = 0;
        int high = A.length - 1;
        int mid;

        while (low <= high) {
            count++;
            mid = (low + high) / 2;
            if (A[mid] == k) {
                return mid;
            } else if (A[mid] < k) {
                low = mid + 1;
            } else {
                high = mid - 1;
            }
        }
        return -1;
    }
}
